// Copyright (C) 2008 Taylor L. Riche <riche@cs.utexas.edu>
//  
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software 
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//

/**
 * 
 */
package appcomp.pathfinder;

import appcomp.entities.*;
import java.util.*;

/**
 * @author riche
 *
 */
public class Pathfinder {
	
	private LinkedList<Path> masterPathList;
	private Type masterRequestType;
	
	public Pathfinder() {
		masterPathList = new LinkedList<Path>();
	}
	
	public int getNumPaths() {
		return masterPathList.size();
	}
	
	public int findPaths(Operator o) {
		System.out.println(o.doesGenerate());
		// call recursion
		Path seed = new Path();
		this.masterRequestType = o.getMasterRequestType();
		LinkedList<Path> pathList = find(o.getPortList(), seed);
		if(!pathList.isEmpty()) {
			masterPathList.addAll(pathList);
		}
		return pathList.size();
	}
	
	private LinkedList<Path> find(ArrayList<Port> portList, Path origPath) {
		
		// TLR 2008/03/14: This recursion works under the assumption you don't 
		// have loops at the moment
		// TLR 2008/04/17: The recursion still works with loops as long as the 
		// ports that are doing the looping are a different request type than the
		// primary request type of the path
		
		LinkedList<Path> pathList = new LinkedList<Path>();
		for (Port port : portList) {
			if (port.getDirection() == Port.Direction.OUT && port.getPortVis() == Port.Visibility.EXTERNAL) {
				if (port.getType().equals(this.masterRequestType)) {
					if (port.getConn() != null) {
						Path newPath = new Path(origPath);
						newPath.addHop(port.getConn());
						if(port.getConn().getOut().doesGenerate()) {
							pathList.add(newPath);
						}
						else {
							LinkedList<Path> tempList = find(port.getConn().getOut().getPortList(), newPath);
							if (!tempList.isEmpty()) {
								pathList.addAll(tempList);
							}
						}
					}
				}
			}
		}
		return pathList;
	}
	
	public void printPaths() {
		for (Path p : this.masterPathList) {
			System.out.println(p.toString());
		}
	}

	/**
	 * @return the masterPathList
	 */
	public LinkedList<Path> getMasterPathList() {
		return masterPathList;
	}

	/**
	 * @return the masterRequestType
	 */
	public Type getMasterRequestType() {
		return masterRequestType;
	}

}
